using System;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using Gtk;
using MySql.Data.MySqlClient;
using Sqlpager;

public partial class DbForm : Gtk.Dialog
{
	DbPage mDb;
	public DbForm(MainWindow main)
	{
		this.Build();
		mDb = main.Db;
		imgWorking.PixbufAnimation = 
			Gdk.PixbufAnimation.LoadFromResource("loading.gif");
		
		Refresh();
		
	}
	
	void OnButtonOkClicked (object sender, System.EventArgs e)
	{
		Working(true);
		lblStatus.Text = "Connecting...";
		System.Threading.Thread myThread = 
			new System.Threading.Thread (new 
				System.Threading.ParameterizedThreadStart (
					this.SecondThread));
		string remember = (checkRemember.Active)?"1":"0";
		mDb = new DbMySql(txtServer.Text,
		                 txtUser.Text,
		                 txtPassword.Text,
		                 txtDb.Text,
		                 remember);
		myThread.Start (mDb);	
		
	}
	void SecondThread (object myValue) 
	{		
		// long task...
		DbPage db = (DbPage)myValue;
		bool connected = db.Connect();	
		if(connected)
			mDb.SaveSettings();
		Gtk.Application.Invoke (delegate {			
 			if(connected){
				lblStatus.Text = "Connected!";
				this.Respond(Gtk.ResponseType.Ok);
			}
			else{
				lblStatus.Text = "Could not connect";
			}
			Working(false);					
			
       	});
	}
	
	void Working(bool b)
    {
		imgWorking.Visible = b;
		lblStatus.Visible = true;
		buttonCancel.Sensitive = !b;
		buttonCreate.Sensitive = !b;
		buttonOk.Sensitive = !b;
		//searching = b;
        //if (!b) searchEntry.GrabFocus();
    }
	void Refresh()
	{
		Dictionary<string,string> dic = mDb.Settings;
		txtServer.Text = dic["server"];
		txtDb.Text = dic["database"];
		if(txtDb.Text=="")
			txtDb.Text = "sqlpager";
		txtUser.Text = dic["user"];
		txtPassword.Text = dic["password"];
		checkRemember.Active = (dic["remember"]=="1")?true:false;
	}

	void OnButtonCreateClicked (object sender, System.EventArgs e)
	{
		mDb = new DbMySql(txtServer.Text,txtUser.Text,txtPassword.Text);
		if(mDb.Connect())
		{
			lblStatus.Text = "Connected.";
			MessageDialog msg = 
				new Gtk.MessageDialog(
			    this,Gtk.DialogFlags.DestroyWithParent,
	           	Gtk.MessageType.Question, Gtk.ButtonsType.OkCancel,
			    "Create tickets database?\n"+
				"ANY TICKETS DATABASE WILL BE DESTROYED!");
			ResponseType resp = (ResponseType)msg.Run();			
			if(resp == ResponseType.Ok)
			{
				Working(true);
				Thread thr = 
					new Thread (new ThreadStart (CreateDatabase));
    			thr.Start ();					
			}	
			msg.Destroy();
		}
		else
		{
			lblStatus.Visible = true;
			lblStatus.Text = Util.Cut(mDb.Error,40);
		}
		
  	}
 
	void CreateDatabase ()
	{
		StreamReader r = null;
		try{
			System.Reflection.Assembly a = 
				System.Reflection.Assembly.GetExecutingAssembly();
			r = new StreamReader(
			    a.GetManifestResourceStream("tickets.sql"));      
			string line = "";
			line = r.ReadLine();
			mDb.Execute(line);	
			line = r.ReadLine();
			mDb.Execute(line);	
			line = r.ReadLine();
			mDb.Execute(line);	
			mDb = new DbMySql(
			    txtServer.Text,txtUser.Text,
			    txtPassword.Text,txtDb.Text,"0");
			Gtk.Application.Invoke (delegate {
	    		lblStatus.Text = "Reading script...";
	    	});
			List<string> lines = new List<string>();
			while((line=r.ReadLine())!=null)
				lines.Add(line);
			int total = lines.Count;
			int perc = total / 10;
			for(int i=0; i<lines.Count;i++)
			{
				mDb.Execute(lines[i]);	
				if((i % perc)==0)
					Gtk.Application.Invoke (delegate {
			    		lblStatus.Text = 
						"Creating "+(10*i/perc).ToString()+"%";
					});
			}
	 		Gtk.Application.Invoke (delegate {
	    		lblStatus.Text = "Done";
				Working(false);
	    	});
		}
	 	catch(Exception ex)
		{
			Console.WriteLine(ex.Message);
		}
		r.Close();
	}
	
}
